import java.io.*;
import java.net.Socket;

public class Client {

    private Socket socketTracker = null;
    private PrintWriter out;
    private BufferedReader in;
    private SeederServ seederServ;
    private MainFrame frame;

	public Client()
	{
		Config.LISTEN_PORT = 40000;//Tools.getFreePort();
		Config.LISTEN_PORT_SEEDER = 40001;//Tools.getFreePort();
		seederServ = new SeederServ();
		seederServ.start();
	}

	public void sendAnnounce()
	{
		this.sendToTracker(Tools.getStringAnnounce(Config.LISTEN_PORT_SEEDER));
	}

	public void sendLook(String filename)
	{
		this.sendToTracker(Tools.getStringLook(filename));
	}

	public void sendGetfile(String key)
	{
		this.sendToTracker(Tools.getStringGetfile(key));
	}

	public void connectToTracker()
	{
		Socket sockcli = null;

		try
		{
			sockcli = new Socket(Config.SERVER_IP, Config.SERVER_PORT);
			this.socketTracker = sockcli;
			this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(this.socketTracker.getOutputStream())), true);
			this.in = new BufferedReader(new InputStreamReader(this.socketTracker.getInputStream()));
		}
		catch (IOException e){}
	}


	public void closeToTracker()
	{
		try{
			if(this.socketTracker != null)
				this.socketTracker.close();
		}catch(IOException e){}
	}

	public void sendToTracker(String s)
	{
		if(this.socketTracker == null || !this.socketTracker.isConnected())
		{
			System.out.println("Socket not connected.");
			return;
		}

		PrintWriter send_s = this.out;
		send_s.print(s);
		send_s.flush();
		Tools.traceFluxSend(s);
	}

	public String receiveFromTracker()
	{
		if(this.socketTracker == null || !this.socketTracker.isConnected())
		{
			System.out.println("Socket not connected.");
			return null;
		}

		try{
			BufferedReader receive_s = this.in;
			String str = receive_s.readLine();
			Tools.treatResponse(str);
			Tools.traceFluxReceive(str);
			return str;
		}catch(IOException e){ return null; }
	}

        public Socket getSocketTracker(){
            return socketTracker;
        }
        
        public PrintWriter getOut(){
            return out;
        }
        
        public BufferedReader getIn(){
            return in;
        }
        
	public void run()
	{
		// Open
		this.connectToTracker();

		// Announce
		this.sendAnnounce();
		this.receiveFromTracker();
                
                frame = new MainFrame(this);

/*
		// GetFile
		this.sendGetfile(Tools.MD5("test_lol.txt"));
		this.receiveFromTracker();
                /* */
	}
}
